import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';

export interface ICheckboxProps {
  name?: string;
  title?: string;
  defaultChecked?: boolean;
  checked?: boolean;
  className?: string;
  style?: React.CSSProperties;
  onToggle?: (checked: boolean) => void;
  onChange?: (e: React.ChangeEvent<HTMLInputElement>) => void;
  disabled?: boolean;
  value?: string;
}

export interface ICheckboxState {
  checked?: boolean;
}
export class Checkbox extends React.Component<ICheckboxProps, ICheckboxState> {
  public static propTypes = {
    name: PropTypes.string,
    title: PropTypes.string,
    defaultChecked: PropTypes.bool,
    checked: PropTypes.bool,
    className: PropTypes.string,
    onToggle: PropTypes.func,
  };
  // 如果传入了外部props，更新到state
  public static getDerivedStateFromProps(nextProps: ICheckboxProps, prevState: ICheckboxState) {
    if (nextProps.checked !== undefined) {
      return {
        checked: nextProps.checked,
      };
    }
    return null;
  }

  constructor(props: ICheckboxProps) {
    super(props);
    this.state = {
      checked: props.defaultChecked || props.checked || false,
    };
    this.handleToggle = this.handleToggle.bind(this);
  }

  public handleToggle(event: React.ChangeEvent<HTMLInputElement>) {
    const checked = event.target.checked;
    const { onToggle, onChange } = this.props;

    if (onToggle || onChange) {
      if (onToggle) {
        onToggle(checked);
      } else if (onChange) {
        onChange(event as any);
      }
    }
    this.setState({
      checked,
    });
  }

  public render() {
    let classString = '';
    const className = this.props.className || '';
    classString = `br-checkbox ${this.state.checked ? 'br-checkbox--checked' : ''} ${className}`;
    return (
      <label className={classNames(classString, this.props.disabled ? `br-checkbox--disabled` : '')}
        style={this.props.style}>
        <span className="br-checkbox__icon" ></span>
        <input
          type="checkbox"
          name={this.props.name}
          checked={this.state.checked}
          className="hidden"
          value={this.props.value}
          onChange={this.handleToggle.bind(this)}
          disabled={this.props.disabled} />
        <span className="br-checkbox__title">{this.props.title || ''}</span>
      </label>
    );
  }
}
